package com.ydles.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.ydles.goods.dao.BrandMapper;
import com.ydles.goods.pojo.Brand;
import com.ydles.goods.service.BrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand queryById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Brand> findPage(int page, int size) {
        //开始分页
        PageHelper.startPage(page,size);
        //select *from tb_brand limit 10 ,5
        List<Brand> brands = brandMapper.selectAll();
        return brands;
    }

    @Override
    public List<Brand> findPage(int page, int size, Map<String, String> searchMap) {

        PageHelper.startPage(page,size);

        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null){
            if (StringUtils.isNotBlank(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
        }

        List<Brand> brandList = brandMapper.selectByExample(example);
        return brandList;
    }


    /**
     * 用户注册
     * 使用BCrypt加密
     * @param brand
     */
    @Override
    public void add(Brand brand) {
        //把明文 转为 密文 存到数据库
        String passWord = brand.getPassWord();
        String hashPw = BCrypt.hashpw(passWord, BCrypt.gensalt());
        brand.setPassWord(hashPw);
        brandMapper.insert(brand);
    }

    /**
     * 用户登录
     */
    @Override
    public Boolean login(Brand brand) {
        String passWord = brand.getPassWord();
        Brand queryBrand = new Brand();
        queryBrand.setName(queryBrand.getName());
        //查询数据库
        Brand dbBrand = brandMapper.selectOne(queryBrand);
        if (dbBrand == null){
            return false;
        }else {
            //对比
            return BCrypt.checkpw(passWord,dbBrand.getPassWord());
        }
    }


}
